package com.imooc.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.bo.UserBo;
import com.imooc.bo.UserLoginBo;
import com.imooc.pojo.Users;
import com.imooc.service.UserService;
import com.imooc.utils.CookieUtils;
import com.imooc.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <h1></h1>
 *
 * @author : dzj
 * @create: 2022-02-14 20:52
 */
@Slf4j
@RestController
@Api(value = "注册登陆", tags = {"用于注册登陆的相关接口"})
@RequestMapping("/passport")
public class PassportController {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private UserService userService;
    @ApiOperation(value = "检查用户是否存在",httpMethod = "GET",notes = "检查用户是否存在note")
    @GetMapping("/usernameIsExist")
    public Result isUserNameExist(@RequestParam String username) throws InterruptedException {

        if(StringUtils.isBlank(username)) {
            return Result.errorMsg("用户名不得为空");
        }
        boolean isExist = userService.queryUsernameIsExist(username);
        return isExist? Result.errorMsg("该用户名已经存在"): Result.ok();

    }
    @ApiOperation(value = "用户注册",httpMethod = "POST",notes = "用户注册")
    @PostMapping("/register")
    public Result register(@Valid @RequestBody UserBo userBo, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException {
        if(bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            List<String> collect = allErrors.stream().map(e -> e.getDefaultMessage()+e.getDefaultMessage()).collect(Collectors.toList());
            return Result.errorMap(collect);
        }
        if(!userBo.getPassword().equals(userBo.getConfirmPassword())) {
            return Result.errorMsg("两次密码不一致, 请确认后重新提交");
        }
        boolean isExist = userService.queryUsernameIsExist(userBo.getUsername());
        if(isExist) {
            return   Result.errorMsg("该用户名已经存在");
        }
        Users user = userService.createUser(userBo);
        setNullProperty(user);
        CookieUtils.setCookie(request,response,"user",objectMapper.writeValueAsString(user),true);

        return Result.ok(user);

    }
    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口",httpMethod = "POST" ,notes = "用户登录")
    public Result login(@Valid @RequestBody UserLoginBo userLoginBo, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException {
        if(bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            List<String> collect = allErrors.stream().map(e -> e.getDefaultMessage()+e.getDefaultMessage()).collect(Collectors.toList());
            return Result.errorMap(collect);
        }
        Users users = userService.queryUser4Login(userLoginBo.getUsername(), userLoginBo.getPassword());
        if(users==null) {
            return Result.errorMsg("用户名或密码错误");
        }
        doLogin(users);
        setNullProperty(users);
        CookieUtils.setCookie(request,response,"user",objectMapper.writeValueAsString(users),true);

        // todo 生成用户token, 存入redis会话
        //todo  , 同步购物车
        return Result.ok(users);

    }
    @ApiOperation(value="用户退出登录",httpMethod = "POST",notes = "用户退出登录note")
    @PostMapping("/logout")
    public Result logout(@RequestParam String userId,HttpServletRequest request, HttpServletResponse response) {
        CookieUtils.deleteCookie(request,response,"user");
        // todo  用户退出登录, 需要清空购物车
        //  todo  分布式会话中需要清除用户数据
        return Result.ok();
    }
    private void setNullProperty(Users user) {
        user.setPassword("");
        user.setEmail("");
        user.setMobile("");
        user.setCreatedTime(null);
        user.setUpdatedTime(null);
        user.setBirthday(null);
    }
    private void doLogin(Users users) {

    }
}
